package com.haifeng.wdsh.common.datasource.handler;

import com.haifeng.wdsh.common.base.exception.BusinessException;
import com.haifeng.wdsh.common.base.util.Rest;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletResponse;

/**
 * <p>
 *  全局异常捕获
 * </p>
 *
 * @author: Haifeng
 * @date: 2020-05-06
 */
@Slf4j
@ControllerAdvice
public class GlobalExceptionAdvice {

    /**
     * 处理异常
     * @param e
     * @param response
     * @return
     */
    @ResponseBody
    @ExceptionHandler(Exception.class)
    public Rest globalException(Exception e, HttpServletResponse response){
        Rest restfulMessage=new Rest();
        restfulMessage.setSuccess(false);
        if(e instanceof BusinessException){
            //手动抛出的业务异常
            BusinessException exception = (BusinessException)e;
            restfulMessage.setCode(exception.getErrCode());
            restfulMessage.setMessage(exception.getMessage());
        }else{
            //其他异常
            restfulMessage.setCode(response.getStatus());
            restfulMessage.setMessage(e.getMessage());
        }
        log.error("【项目发生异常：】"+restfulMessage.toString());
        e.printStackTrace();
        return restfulMessage;
    }
}
